import React, { Component, createRef } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Space,
  Input,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import Channel from 'components/Channel'
import Quill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { baseURL } from 'utils/request'
import { addArticle, getArticleById, uploadArticle } from 'api/article'

export default class ArticlePublish extends Component {
  state = {
    type: 1,
    fileList: [],
    previewVisible: false,
    previewImage: '',
    artId: this.props.match.params.id,
  }
  formDraft = createRef()
  async add(values, draft) {
    const { type, fileList, artId } = this.state
    if (fileList.length !== type) {
      return message.warning('图片上传数量不正确')
    }
    const images = fileList.map((item) => {
      return item.url || item.response.data.url
    })
    if (artId) {
      // 编辑文章
      await uploadArticle(
        {
          ...values,
          cover: {
            type,
            images,
          },
          id: artId,
        },
        draft
      )
    } else {
      // 增加文章
      await addArticle(
        {
          ...values,
          cover: {
            type,
            images,
          },
        },
        draft
      )
    }
    message.success(`${artId ? '编辑' : '添加'}文章成功`)
    this.props.history.push('/home/list')
  }
  onFinish = (values) => {
    this.add(values)
  }
  onDraft = async () => {
    const values = await this.formDraft.current.validateFields()
    this.add(values, true)
  }
  onChange = (e) => {
    this.setState({ type: e.target.value, fileList: [] })
  }
  updateImg = ({ fileList }) => {
    this.setState({
      fileList,
    })
  }
  handlePreview = (file) => {
    const url = file.url || file.response?.data?.url
    this.setState({
      previewVisible: true,
      previewImage: url,
    })
  }
  handleCancel = () => {
    this.setState({
      previewVisible: false,
      previewImage: '',
    })
  }
  beforeUpload = (file) => {
    const { size, type } = file
    if (size > 1024 * 500) {
      message.warning('上传文件大小不能超过500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/png', 'image/jpeg'].includes(type)) {
      message.warning('图片格式需要为png、jpeg')
      return Upload.LIST_IGNORE
    }
    return true
  }
  async componentDidMount() {
    console.log('ArticlePublish组件挂载')
    const { artId } = this.state
    if (artId) {
      const { data } = await getArticleById(artId)
      const { type, images } = data.cover
      const fileList = images.map((item) => ({ url: item }))
      this.setState({ fileList, type })
      this.formDraft.current.setFieldsValue({ ...data, type })
    }
  }
  render() {
    const { type, fileList, previewVisible, previewImage, artId } = this.state
    return (
      <div className={styles.root}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {artId ? '编辑文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            size="large"
            ref={this.formDraft}
            labelCol={{ span: 4 }}
            validateTrigger={['onBlur', 'onChange']}
            onFinish={this.onFinish}
            initialValues={{
              content: '',
              type,
            }}
          >
            {/* 标题 */}
            <Form.Item
              label="标题"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入文章标题',
                },
              ]}
            >
              <Input
                style={{ width: 400 }}
                placeholder="请输入文章标题"
              ></Input>
            </Form.Item>
            {/* 选择频道 */}
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[
                {
                  required: true,
                  message: '请选择频道',
                },
              ]}
            >
              <Channel />
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.onChange}>
                <Radio value={1}>1图</Radio>
                <Radio value={3}>3图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 上传图片 */}
            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Upload
                  listType="picture-card"
                  name="image"
                  fileList={fileList}
                  action={`${baseURL}/upload`}
                  onChange={this.updateImg}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length < type && <PlusOutlined />}
                </Upload>
              </Form.Item>
            )}
            {/* 内容 */}
            <Form.Item
              label="内容"
              name="content"
              rules={[
                {
                  required: true,
                  message: '请输入内容',
                },
              ]}
            >
              <Quill />
            </Form.Item>
            {/* 提交 */}
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  {artId ? '编辑文章' : '发布文章'}
                </Button>
                <Button onClick={this.onDraft}>存为草稿</Button>
              </Space>
            </Form.Item>
          </Form>
          {previewVisible && (
            <Modal
              visible={previewVisible}
              title={'图片预览'}
              footer={null}
              onCancel={this.handleCancel}
            >
              <img alt="" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          )}
        </Card>
      </div>
    )
  }
}
